package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author mrchen
 * @date 2022/7/28 16:17
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    //oss默认存储的文件夹名称
    @Value("${file.oss.prefix}")
    private String prefix;

    //外界访问oss路劲
    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 上传图片接口
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 0. 参数校验 (文件不为空， 用户登陆， 校验文件 【.jpg .png .jpeg .gif】 )
        if(multipartFile == null || multipartFile.getSize() ==0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上传的文件不能为空");
        }
        // 截取文件的后缀
        String originName = multipartFile.getOriginalFilename(); // 原始的文件名称   sdsdsd.dsfsdfsd.meinv004.jpg
        String suffix = originName.substring(originName.lastIndexOf("."));
        //checkFileSuffix方法检验文件后缀名是否与规定的后缀名相同，相同则为ture
        if(!checkFileSuffix(suffix)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上传的文件格式不符合要求  【.jpg .png .jpeg .gif】");
        }
        // 获取当前登陆用户
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录再继续操作");
        }
        // 1. 将文件上传到OSS 先给文件生成一个随机数
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        try {
            // 文件OSS中的地址                                         随机生成uuid作为文件的名称 + 文件后缀
            String store = fileStorageService.store(prefix, fileName + suffix, multipartFile.getInputStream());
            // 2. 素材表添加一条数据
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());// 登陆用户id
            wmMaterial.setUrl(store);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0); // 0 未收藏 1 收藏
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);
            return ResponseResult.okResult();
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文件上传失败,服务器出现异常");
        }
        return null;
    }
    private boolean checkFileSuffix(String suffix) {
        List<String> allowList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif");
        for (String allowSuffix : allowList) {
            if (suffix.equals(allowSuffix)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        // 1. 校验参数
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 执行查询
        // 2.1 分页查询基本参数
        Page<WmMaterial> pageReq = new Page<>(dto.getPage(), dto.getSize());
        // 2.2 参数查询额外条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        // 如果收藏字段不为空 按照是否收藏条件查询
        if(WemediaConstants.COLLECT_MATERIAL.equals(dto.getIsCollection())){
            // where collection = 1
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
            // 按照登陆用户id查询
        queryWrapper.eq(WmMaterial::getUserId,user.getId());
            // 按照创建时间降序排序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
          //执行查询，返回查询结果 pageResult
        IPage<WmMaterial> pageResult = page(pageReq, queryWrapper);
        // 3. 封装查询结果  records为结果集合
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),records);
        return result;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;


    /**
     * 删除图片
     * @param id
     * @return
     */
    @Transactional
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1. 根据id查询素材数据
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材不存在");
        }
        // 2.判断素材是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if(count > 0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"素材被引用，无法删除");
        }
        // 3. 从数据库中删除数据
        this.removeById(id);
        // 4. 从OSS中删除对应素材
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult();
    }
    /**
     * 收藏与取消收藏
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        WmMaterial material = getById(id);
        if (material == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材信息不存在");
        }
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if(!material.getUserId().equals(uid)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己上传的素材");
        }
        //设置是否收藏
        material.setIsCollection(type);
        updateById(material);
//        update(Wrappers.<WmMaterial>lambdaUpdate()  // 如果只想修改指定字段 可以使用此方法
//                .set(WmMaterial::getIsCollection,type)
//                .eq(WmMaterial::getId,id)
//                .eq(WmMaterial::getUserId,uid));
        return ResponseResult.okResult();
    }



    public static void main(String[] args) {
        System.out.println();
    }
}